package com.demoo.zjsu.util.javamail;

import org.springframework.mail.MailMessage;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.*;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * Created by jshjsh on 2016/8/13.
 */
public abstract class SpringMailSender {



     Target target;

     SimpleMailMessage simpleMailMessage;

     MimeMessage mimeMessage;


    public JavaMailSenderImpl initSender(){
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost(Mail.getHOST());
        sender.setPort(Mail.getPORT());
        sender.setDefaultEncoding(Mail.getDefaultEncoding());
        sender.setUsername(Mail.getUsername());
        sender.setPassword(Mail.getPassword());
        Properties properties = new Properties();
        properties.put("mail.smtp.auth","true");  // 验证用户名和密码
        properties.put("mail.smtp.timeout","0");
        sender.setJavaMailProperties(properties);
        return sender;
    }

    public abstract void initMessage();


    public void sendSimpleMail(){
        JavaMailSenderImpl sender = initSender();
        initMessage();
        sender.send(simpleMailMessage);
    }

    public void sendMimeMail() throws MessagingException {
        JavaMailSenderImpl sender = initSender();
        initMessage();
        mimeMessage = sender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
        sender.send(mimeMessage);
    }

    public Target getTarget() {
        return target;
    }

    public void setTarget(Target target) {
        this.target = target;
    }
}
